package cc.md888.app.application.activatecode;

import cc.md888.app.domain.entity.ActivateCode;
import cc.md888.app.infr.dao.ActivateCodeDao;
import cc.md888.app.model.activatecode.ActivateCodeVO;
import cc.md888.app.model.activatecode.SendEmailActivateCodeCmd;
import cc.md888.app.model.user.SendActivateEmailCmd;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.UUID;

@Component
public class ActivateCodeService
{


    @Autowired
    private ActivateCodeDao activateCodeDao;

    @Autowired
    private ActivateEmailService activateEmailService;

    @Autowired
    private ActivateCodeGenerator activateCodeGenerator;


    /**
     * 获取激活码
     * @param token
     * @return
     */
    public ActivateCode getByToken(String token){
        return activateCodeDao.getOne(
                Wrappers.<ActivateCode>query().eq(
                        ActivateCode.TOKEN, token
                )
        );
    }

    /**
     * 发送激活邮件
     * @param cmd
     * @return
     */
    public ActivateCodeVO sendActivateEmail(SendActivateEmailCmd cmd){
        SendEmailActivateCodeCmd sendCmd = new SendEmailActivateCodeCmd();

        String code = activateCodeGenerator.gen();
        String token = UUID.randomUUID().toString().replace("-", "");

        sendCmd.setEmail(cmd.getEmail());
        sendCmd.setCode(code);
        activateEmailService.send(sendCmd);

        ActivateCode activateCode = new ActivateCode();
        activateCode.setEmail(cmd.getEmail());
        activateCode.setCode(code);
        activateCode.setToken(token);
        activateCode.setExpireAt(LocalDateTime.now().plusMinutes(5));
        activateCode.setId(IdWorker.getId());
        activateCodeDao.save(activateCode);

        ActivateCodeVO activateCodeVO  = new ActivateCodeVO();
        BeanUtils.copyProperties(activateCode, activateCodeVO);
        return activateCodeVO;
    }
}
